import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'
// 同步引入组件
// import Register from '@/views/Register'
// import Layout from '@/views/Layout'
// import Detail from '@/views/Detail'
// import Article from '@/views/Article'
// import Collect from '@/views/Collect'
// import Like from '@/views/Like'
// import User from '@/views/User'
const Register = () => import('@/views/Register')
const Layout = () => import('@/views/Layout')
const Detail = () => import('@/views/Detail')
const Article = () => import('@/views/Article')
const Collect = () => import('@/views/Collect')
const Like = () => import('@/views/Like')
const User = () => import('@/views/User')

// 将登录改造成路由懒加载
// import Login from '@/views/Login'
const Login = () => import('@/views/Login')

Vue.use(VueRouter)

const router = new VueRouter({
  // 配置路由规则的数组
  routes: [
    // 一个对象表示一条路由规则
    { path: '/register', component: Register },
    { path: '/login', component: Login },
    { path: '/detail/:id', component: Detail },
    {
      path: '/',
      component: Layout,
      redirect: '/article', // 重定向
      children: [ // 二级路由
        { path: '/article', component: Article },
        { path: '/collect', component: Collect },
        { path: '/like', component: Like },
        { path: '/user', component: User }
      ]
    }
  ]
})

const whiteList = ['/register', '/login']
// 一旦添加了全局前置守卫, 每次页面跳转都会经过此处, 如果此处不放行则无法跳转页面
// 回调函数有三个参数
// 1. to: 到哪里去
// 2. from: 从哪里来
// 3. next(): 是一个函数
//  a. 直接调用不传参表示放行
//  b. 调用传入指定路径表示强制跳转到指定路径, 类似于重定向
//  c. 调用传入 false 表示不放行
router.beforeEach((to, from, next) => {
  // 守卫: 页面跳转时拦截一下
  // to.path => /article /collect /register
  // console.log('到哪里去:', to.path, '从哪里来:', from.path)
  // 获取 token
  const token = getToken()
  if (token) {
    // 有 token 就放行
    next()
  } else {
    // 判断是否在白名单里
    // 白名单: 登录页和注册页
    // if (to.path === '/register' || to.path === '/login') {
    // 判断用户访问的目标是否在白名单列表中, 如果在就放行
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // 拦截到登录
      next('/login')
    }
  }
})

export default router
